import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import main from "@/router/duli-router/main";
import store from '../store/router/router'


  const routes: Array<RouteRecordRaw>=[
    ...main,
  ]
  const router = createRouter({
    history: createWebHashHistory(),
    routes
  })
  //拦截
router.beforeEach((to,from,next)=>{
  // console.log(to);
  if(to.path=="/login"){
    next()
  }
  //未登录就跳转登陆页面
  const token=sessionStorage.getItem("current_authorization");


  if(!token){
    next("/login")
  }
  else{
    // next()
    //动态获取路由，有哪些返回哪些
    let add:any=getRoutes()//获取动态路由
    // console.log(add)
    
    let currentRoutes:any=router.options.routes;//获取已经存在的路由设置
    currentRoutes=JSON.parse(JSON.stringify(currentRoutes));
    if(router.getRoutes().length<=currentRoutes.length&&add.length>0){
      //proxy代替了object
      add=JSON.parse(JSON.stringify(add))
      add.forEach((item:any)=>{
        let path=item.menuUrl;
        let name=item.componentName;
        // 后面写 component:() => import(`../views/${item.componentView}`) 会报错，所以拆分之后重新拼接一下字符串就不会报错
        let myComponent=item.componentView.split(".")//  [ role/About, vue]
        let has=currentRoutes.some((current:any)=>{
          if(current.path==path){
            return true
          }
        });
        if(!has){
          router.addRoute({
            path:path,
            name:name,
            component:() => import(`../views/${myComponent[0]}.vue`)
          })
        }
        
        
  
      })
    }

  }

  next()

})

function getRoutes() {
  let menuInfo=[...store.state.userData.menuInfo];

  if(menuInfo.length>0){
    menuInfo.map((item)=>{
      if(item.menuChilds.length>0){
        for(let i=0;i<item.menuChilds.length;i++){
          menuInfo.push(item.menuChilds[i])
        }
      }
    })
  }
  return menuInfo;
}



export default router
